﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using AMM.Business.Config;
using AMM.CustomClassLibrary;
using AMM.Model;

namespace AMM.CommonControls {
    public partial class AttachmentEdit : UserControl {

        private string _text, _folder;
        private Attachment _existAttachment;
        private ConfigurationProcessor _configProcessor;
        private AttachmentProcessor _attachmentProcessor;

        [Bindable(true)]
        public override string Text {
            get { return this._text; }
            set {
                if (this.InvokeRequired) {
                    this.Invoke(new MethodInvoker(delegate() { this.SetText(value); }));
                }
                else {
                    this.SetText(value);
                }
            }
        }

        private void SetText(string value) {
            this._text = value;
            if (!string.IsNullOrEmpty(this._text)) {
                this.btnDownload.Enabled = true;
                this._existAttachment = this._attachmentProcessor.FetchAttachmentById(int.Parse(this._text));
                this.lblInformation.Text = string.Format("{0} - {1}",
                    this._existAttachment.OriginalName, MethodHelper.GetFileSize(this._existAttachment.FileSize));
            }
            else {
                this.Reset();
            }
        }

        public void Reset() {
            this._text = string.Empty;
            this.btnDownload.Enabled = false;
            this.lblInformation.Text = "请选择文件";
        }

        public AttachmentEdit() {
            this.InitializeComponent();
        }

        private void AttachmentEdit_Load(object sender, EventArgs e) {
            if (this.DesignMode) { return; }
            this._text = string.Empty;
            this._configProcessor = new ConfigurationProcessor();
            this._attachmentProcessor = new AttachmentProcessor();
            this._folder = this._configProcessor.FetchConfigurationByKeyCode("AttachmentFolder").KeyValue;
        }

        private void btnSelect_Click(object sender, EventArgs e) {
            if (this.ofdSelectFile.ShowDialog() == DialogResult.OK) {
                this.lblInformation.Text = "上传文件中...";
                try {
                    FileInfo fi = new FileInfo(this.ofdSelectFile.FileName);
                    if (fi.Length > long.Parse(this._configProcessor.FetchConfigurationByKeyCode("AttachmentSize").KeyValue)) {
                        this.lblInformation.Text = "文件太大，上传失败！";
                        return;
                    }

                    Attachment attachment = new Attachment();
                    attachment.AttachmentId = Guid.NewGuid().GetHashCode();
                    attachment.OriginalName = this.ofdSelectFile.SafeFileName;
                    attachment.FileSize = (int)fi.Length;
                    attachment.FileExtension = fi.Extension;

                    string destinationFileName = string.Format(@"{0}\{1}{2}", this._folder, attachment.AttachmentId, fi.Extension);
                    if (!Directory.Exists(this._folder)) { Directory.CreateDirectory(this._folder); }
                    fi.CopyTo(destinationFileName, true);

                    this._attachmentProcessor.Insert(attachment);
                    this._text = attachment.AttachmentId.ToString();
                    // using DataBindings, we have to raise the event to tell UserControl that text changed
                    OnTextChanged(new EventArgs());
                    this.lblInformation.Text = string.Format("{0} - {1}",
                        this.ofdSelectFile.SafeFileName, MethodHelper.GetFileSize(fi.Length));
                    this.btnDownload.Enabled = false;
                }
                catch (Exception ex) {
                    Logger.Error(ex.Message, ex);
                    this.lblInformation.Text = "上传文件失败！";
                }
            }
        }

        private void btnDownload_Click(object sender, EventArgs e) {
            if (this.fbdSaveFile.ShowDialog() == DialogResult.OK) {
                string sourceFileName = string.Format(@"{0}\{1}{2}",
                    this._folder, this._existAttachment.AttachmentId, this._existAttachment.FileExtension);
                string targetFileName = string.Format(@"{0}\{1}",
                    this.fbdSaveFile.SelectedPath, this._existAttachment.OriginalName);
                File.Copy(sourceFileName, targetFileName, false);
                Process.Start("Explorer.exe", string.Format(@"/select,{0}\{1}",
                    this.fbdSaveFile.SelectedPath, this._existAttachment.OriginalName));
            }
        }
    }
}
